package top.zhangjianyong.tools.indicator.strategy.impl;

import org.springframework.stereotype.Component;
import top.zhangjianyong.tools.entity.ETFData;
import top.zhangjianyong.tools.indicator.context.IndicatorContext;
import top.zhangjianyong.tools.indicator.model.TechnicalIndicatorResult;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;

/**
 * 量价交互指标计算器
 * 计算价格变化率与成交量变化率的乘积
 *
 * @author zhangjianyong
 * @date 2024/01/01
 */
@Component
public class VolumePriceInteractionIndicator extends AbstractIndicator {

    private static final String INDICATOR_NAME = "VOLUME_PRICE_INTERACTION";

    @Override
    public String getName() {
        return INDICATOR_NAME;
    }

    @Override
    public int getMinDataSize() {
        return 2; // 至少需要2个数据点来计算变化率
    }

    @Override
    protected TechnicalIndicatorResult doCalculate(IndicatorContext context) {
        List<ETFData> dataList = context.getDataList();

        if (dataList.size() < 2) {
            return TechnicalIndicatorResult.failure(getName(), "数据不足，需要至少2个数据点");
        }

        ETFData current = dataList.get(dataList.size() - 1);
        ETFData previous = dataList.get(dataList.size() - 2);

        // 计算价格变化率
        BigDecimal priceChangeRate = BigDecimal.ZERO;
        if (previous.getValue().compareTo(BigDecimal.ZERO) != 0) {
            priceChangeRate = current.getValue().subtract(previous.getValue())
                .divide(previous.getValue(), 4, RoundingMode.HALF_UP)
                .multiply(new BigDecimal(100));
        }

        // 计算成交量变化率
        BigDecimal volumeChangeRate = BigDecimal.ZERO;
        Long currentVolume = current.getVolume() != null ? current.getVolume() : 0L;
        Long previousVolume = previous.getVolume() != null ? previous.getVolume() : 0L;

        if (previousVolume != 0) {
            volumeChangeRate = BigDecimal.valueOf(currentVolume - previousVolume)
                .divide(BigDecimal.valueOf(previousVolume), 4, RoundingMode.HALF_UP)
                .multiply(new BigDecimal(100));
        }

        // 计算量价交互（价格变化率 × 成交量变化率）
        BigDecimal interaction = priceChangeRate.multiply(volumeChangeRate);

        TechnicalIndicatorResult result = TechnicalIndicatorResult.success(getName());
        result.addValue("price_change_rate", priceChangeRate.setScale(2, RoundingMode.HALF_UP));
        result.addValue("volume_change_rate", volumeChangeRate.setScale(2, RoundingMode.HALF_UP));
        result.addValue("volume_price_interaction", interaction.setScale(4, RoundingMode.HALF_UP));

        return result;
    }
}

